import { createRouter, createWebHistory } from 'vue-router'
import { getToken, getUserRole } from '@/utils/auth'
import Layout from '@/layout/Index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [{
        path: 'home',
        name: 'home',
        component: () => import('@/views/reader/Home.vue'),
        meta: { title: '首页', icon: 'HomeFilled', requiresAuth: true }
      }]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/components/auth/Login.vue'),
      meta: { hidden: true }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/components/auth/Register.vue'),
      meta: { hidden: true }
    },
    {
      path: '/admin',
      component: Layout,
      meta: { title: '管理中心', icon: 'Setting', roles: ['admin'], requiresAuth: true },
      redirect: '/admin/users',
      children: [
        {
          path: 'users',
          name: 'admin-users',
          component: () => import('@/views/admin/UserManagement.vue'),
          meta: { title: '用户管理', icon: 'User' }
        },
        {
          path: 'novels',
          name: 'admin-novels',
          component: () => import('@/views/admin/NovelManagement.vue'),
          meta: { title: '小说管理', icon: 'Notebook' }
        },
        {
          path: 'add-admin',
          name: 'admin-add',
          component: () => import('@/views/admin/AdminCreation.vue'),
          meta: { title: '新增管理员', icon: 'Plus' }
        }
      ]
    },
    {
      path: '/novels',
      component: Layout,
      redirect: '/novels/list',
      meta: { title: '小说', icon: 'Reading', requiresAuth: true },
      children: [
        {
          path: 'list',
          name: 'novel-list',
          component: () => import('@/views/reader/NovelList.vue'),
          meta: { title: '小说列表', icon: 'List' }
        },
        {
          path: 'category',
          name: 'novel-category',
          component: () => import('@/views/reader/Category.vue'),
          meta: { title: '分类小说', icon: 'Grid' }
        },
        {
          path: ':id',
          name: 'novel-detail',
          component: () => import('@/views/reader/NovelDetail.vue'),
          meta: { title: '小说详情', hidden: true }
        }
      ]
    },{
      path: '/reviews',
      component: Layout,
      children: [{
        path: '',
        name: 'reviews',
        component: () => import('@/views/Reviews.vue'),
        meta: { title: '书评', icon: 'ChatDotRound', requiresAuth: true }
      }]
    },
  ]
})

router.beforeEach((to, from, next) => {
  const hasToken = getToken();

  // 如果目标路由需要认证
  if (to.meta.requiresAuth) {
    // 如果没有 token，重定向到登录页
    if (!hasToken) {
      next({ name: 'login', query: { redirect: to.fullPath } });
    } else {
      // 如果有 token，检查角色权限
      const userRole = getUserRole();
      if (to.meta.roles && !to.meta.roles.includes(userRole)) {
        // 如果角色不匹配，重定向到首页（或无权限页面）
        next({ name: 'home' });
      } else {
        // 权限通过
        next();
      }
    }
  } else {
    // 如果目标路由不需要认证（如登录页）
    // 但用户已经登录，则直接重定向到首页
    if (hasToken && (to.name === 'login' || to.name === 'register')) {
      next({ name: 'home' });
    } else {
      // 否则，正常访问
      next();
    }
  }
});

export default router